package com.nbsaas.boot.security.realm;

import com.nbsaas.boot.security.api.AuthorizationApi;
import com.nbsaas.boot.security.token.DataToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.Collection;

public class DataRealm<T> extends AuthorizingRealm {

    @Resource
    private AuthorizationApi authorizationApi;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (authorizationApi != null) {
            info.addRoles(authorizationApi.loadRoles());
            info.addStringPermissions(authorizationApi.loadPermissions());
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        DataToken<T> token = (DataToken<T>) authenticationToken;
        return new SimpleAuthenticationInfo(token.getData(), token.getPassword(), getName());
    }

    public Collection<String> getStringPermissions(PrincipalCollection principals) {

        AuthorizationInfo authorizationInfo = getAuthorizationInfo(principals);
        if (authorizationInfo != null) {
            return authorizationInfo.getStringPermissions();
        }
        return null;

    }

    public Collection<String> permissions() {
        Subject currentUser = SecurityUtils.getSubject();

        if (currentUser.isAuthenticated()) {
            PrincipalCollection principals = currentUser.getPrincipals();
            AuthorizationInfo authorizationInfo = getAuthorizationInfo(principals);
            if (authorizationInfo != null) {
                return authorizationInfo.getStringPermissions();
            }
        }
        return null;
    }




    /**
     * 清除指定用户的认证信息缓存
     */
    public void clearAuthenticationCache(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    /**
     * 清除指定用户的授权信息缓存
     */
    public void clearAuthorizationCache(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }
}
